package com.example.demo.thread;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author Code Farmer
 * @date 2020/5/23 14:19
 */
public class CasABADemo2 {

    private static AtomicStampedReference<Integer> count = new AtomicStampedReference<>(0, 1);

    public static void main(String[] args) {
        System.out.println("mainThread 当前count值为： " + count.getReference() + ",版本号为：" + count.getStamp());
        Thread mainThread = new Thread(() -> {
            try {
                int expectStamp = count.getStamp();
                int updateStamp = expectStamp + 1;
                int expectCount = count.getReference();
                int updateCount = expectCount + 1;
                System.out.println("mainThread 期望值：" + expectCount + ", 修改值：" + updateCount);
                Thread.sleep(2000);//休眠2000s ，释放cpu

                boolean result = count.compareAndSet(expectCount, updateCount, expectStamp, updateStamp);
                System.out.println("mainThread 修改count ： " + result);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        });

        Thread otherThread = new Thread(() -> {
            try {
                Thread.sleep(20);//确保主线程先获取到cpu资源
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            count.compareAndSet(count.getReference(), count.getReference() + 1, count.getStamp(), count.getStamp() + 1);
            System.out.println("其他线程先修改 count 为：" + count.getReference() + " ，版本号：" + count.getStamp());
            count.compareAndSet(count.getReference(), count.getReference() - 1, count.getStamp(), count.getStamp() + 1);
            System.out.println("其他线程又修改 count 为：" + count.getReference() + " ，版本号：" + count.getStamp());
        });

        mainThread.start();
        otherThread.start();

    }

}
